/*
 * 注册行为
 */
package cn.edu.ntu.yyl.controller;

import cn.edu.ntu.yyl.pojo.user.UserInfo;
import cn.edu.ntu.yyl.service.UserActionService;
import cn.edu.ntu.yyl.tool.code.Check;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class RegisterServlet extends HttpServlet {
	@Autowired
	UserActionService registService;
	UserInfo userInfo = new UserInfo();
	 @RequestMapping("/register.do")
	 protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			 response.setContentType("text/html;charset=UTF-8");
		 	/*获取表单中的用户名*/
	        String userName = request.getParameter("username");
	        /*获取表单中的邮箱*/
	        String email = request.getParameter("email");
	        /*获取表单中的密码*/
	        String password = request.getParameter("pwd");
	        /*获取表单中的确认密码*/
	        String RePassword = request.getParameter("confirmPwd");
	        /*核对数据*/
	        /*确认密码和验证码*/
	        if(!password.equals(RePassword)) {response.getWriter().println("两次密码输入不一致！");}
	        else{
	        	 Check check = new Check();
	 	        /*获取验证码检查结果*/
	 	        check.doPost(request,response);
	 	        if(!check.getResult()) {response.getWriter().println("验证码输入不正确！");}
	 	        else {
		 	        /*写入数据*/
		 	        userInfo.setUsername(userName);
		 	        userInfo.setPassword(password);
		 	        userInfo.setEmail(email);
		 	        userInfo.setNickname(userName);/*默认昵称为注册时的用户名*/
		 	        userInfo.setRealname(userName);/*默认真名为注册时的用户名*/
		 	        int result = registService.addnewuser(userInfo);
		 	        //大于等于1表示成功
		 	        if (result>=1) {
						response.getWriter().println("注册成功");
		 	        }
		 	        else {
		 	        	switch(result){
							case -1 : {response.getWriter().println("用户名已被占用");}
							case -2 : {response.getWriter().println("该邮箱已经注册");}
							default : {response.getWriter().println("注册失败");}
						}
					}
	 	        }
        	
	        }
	 }
}
